//$Id: RegisterAction.java,v 1.20 2007/02/25 19:09:39 gavin Exp $
package pl.edu.agh.iosr.gamblingzone.action;

import static org.jboss.seam.ScopeType.EVENT;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;

import pl.edu.agh.iosr.gamblingzone.model.BettingSlip;
import pl.edu.agh.iosr.gamblingzone.model.User;
import pl.edu.agh.iosr.gamblingzone.validators.UserValidator;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.UserDAOBean;

/**
 * The Class MyRegisterAction.
 */
@Stateful
@Scope(EVENT)
@Name("register")
public class MyRegisterAction implements MyRegister {

	/** The user. */
	@In
	private User user;

	/** The em. */
	@PersistenceContext
	private EntityManager em;

	/** The faces messages. */
	@In
	private FacesMessages facesMessages;

	/** The verify. */
	private String verify;

	/** The registered. */
	private boolean registered;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyRegister#register()
	 */
	public void register() {
		if (user.getPassword().equals(User.computeSHA1(verify))) {
			UserDAOBean userDAO = new UserDAOBean();
			userDAO.setEntityManager(em);

			// Authenticate user via DAO
			if (userDAO.findByLogin(user.getLoginName()) != null) {
				facesMessages.addToControl("username",
						"Username #{user.loginName} already exists");
			} else if (!UserValidator.isUserMature(user)) {
				facesMessages
						.addToControl("username", "You have to be over 21");
			} else {
				user.addRole("aaa");
				user.setTempBettingSlip(new BettingSlip());
				userDAO.makePersistent(user);
				facesMessages
						.add("Successfully registered as #{user.loginName}");
				registered = true;
			}
		} else {
			facesMessages.addToControl("verify", "Re-enter your password");
			verify = null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyRegister#invalid()
	 */
	public void invalid() {
		facesMessages.add("Please try again");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyRegister#isRegistered()
	 */
	public boolean isRegistered() {
		return registered;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyRegister#getVerify()
	 */
	public String getVerify() {
		return verify;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyRegister#setVerify(java.lang.String)
	 */
	public void setVerify(String verify) {
		this.verify = verify;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.edu.agh.iosr.gamblingzone.action.MyRegister#destroy()
	 */
	@Destroy
	@Remove
	public void destroy() {
		em.flush();
	}
}
